<?php

namespace app\nideshop\controller;

use think\Db;
use app\nideshop\validate\CategoryValidate;

class Category extends Base
{
	/**
	 * 接收请求参数
	 * @var [type]
	 */
	protected $datas;

	/**
	 * 对应数据表
	 * @var [type]
	 */
	protected $table = 'category';

	/**
	 * 分类列表
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-23T11:55:57+0800
	 * @return   [type]                   [description]
	 */
	public function indexAction()
	{
		$this->datas = $this->params;
		$categoryId = isset($this->datas['id']) ? $this->datas['id'] : '';
		$data = Db::name($this->table)->where('parent_id', 0)->limit(10)->select();
		$currentCategory = '';
		if ($categoryId) {
        	$currentCategory = Db::name($this->table)->where('id', $categoryId)->find();
      	}
      	if (empty($currentCategory)) {
      		$currentCategory = $data[0];
      	}
      	if ($currentCategory && isset($currentCategory['id'])) {
      		$list = Db::name($this->table)->where('parent_id', $currentCategory['id'])->select();
      		$currentCategory['subCategoryList'] = $list;
      		$data[0]['subCategoryList'] = $list;
      	}
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'categoryList' => $data,
				'currentCategory' => $currentCategory
			]
		]);
	}

	/**
	 * 获得分类数据
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-22T00:02:40+0800
	 * @return   [type]                   [description]
	 */
	public function categoryAction()
	{
		$this->datas = $this->params;
		$validate = new CategoryValidate();
		if (!$validate->scene('cate')->check($this->datas)) {
			return json(['errno' => 1, 'errmsg' => $validate->getError(), 'data' => []]);
		}
		$id = $this->datas['id'];
		$currentCategory = Db::name($this->table)->where('id', $id)->find();
		$parentCategory = (object)Db::name($this->table)->where('id', $currentCategory['parent_id'])->find();
		$brotherCategory = Db::name($this->table)->where('parent_id', $currentCategory['parent_id'])->select();
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'currentCategory' => $currentCategory,
				'parentCategory' => $parentCategory,
				'brotherCategory' => $brotherCategory
			]
		]);
	}

	public function currentAction()
	{
		$this->datas = $this->params;
		$categoryId = $this->datas['id'];
		$currentCategory = null;
		if (!empty($categoryId))
		{
			$currentCategory = Db::name('category')
			->where('id', $categoryId)
			->find();
		}
		if (!empty($currentCategory) && !empty($currentCategory['id'])) 
		{
			$currentCategory['subCategoryList'] = Db::name('category')
			->where('parent_id', $currentCategory['id'])
			->select();
		}

		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'currentCategory' => $currentCategory
			]
		]);
	}
}